package com.hooware.utils;

import com.hooware.dao.ILogDao;
import com.hooware.domain.SysLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.SourceLocation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.Date;

@Component
@Aspect
public class AopLog {

    @Autowired
    ILogDao iLogDao;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SysLog sysLog;

    /*
    *   private String id;
        private Date visitTime;
        private String visitTimeStr;
        private String username;
        private String ip;
        private String url;
        private Long executionTime;
        private String method;
    * */

    public Object saveLog(ProceedingJoinPoint pjp) throws Throwable {

        // 获取session域对象
        HttpSession session = request.getSession();

        // 获取方法参数
        Object[] args = pjp.getArgs();

        // 1.获取访问时间
        Date visitTime = new Date();

        // 执行方法
        Object returnValue = pjp.proceed(args);

        // 2.获取用户名
        SecurityContextImpl ssc = (SecurityContextImpl)session.getAttribute("SPRING_SECURITY_CONTEXT");
        String username = ssc.getAuthentication().getName();
        //3.获取ip
        String ip = request.getRemoteAddr();
        //4.获取url
        String url = request.getRequestURL().toString();

        //5.获取访问时间
        long executionTime = System.currentTimeMillis() - visitTime.getTime();

        //6.获取访问方法
        String method = pjp.getSignature().getName();

        // 写入日志
        sysLog.setVisitTime(visitTime);
        sysLog.setUsername(username);
        sysLog.setIp(ip);
        sysLog.setUrl(url);
        sysLog.setExecutionTime(executionTime);
        sysLog.setMethod(method);

        iLogDao.saveLog(sysLog);
        System.out.println("sysLog写入成功... + " + sysLog);

        return returnValue;
    }
}
